package cn.com.generaldata.os.util;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.bee.tl.core.Config;
import org.bee.tl.core.Context;
import org.bee.tl.core.Function;
import org.bee.tl.core.GroupTemplate;
import org.bee.tl.core.Template;

public class Beetls {
	private static GroupTemplate me = null;

	public static class ToStringFunction implements Function {
		@Override
		public String call(Object[] paras, Context ctx) {
			return String.valueOf(paras[0]);
		}
	}

	static {
		init();

	}

	private static void init() {
		Config config;
		try {
			config = new Config();
			me = config.createGroupTemplate();
			me.enableChecker(10); // 每10秒检查一下模板文件是否更新,如果未调用，或者设置为0，则不检查更新
			// 其他配置
			me.enableOptimize(); // 允许优化成class代码运行
			me.registerFunction("str", new ToStringFunction());
		} catch (IOException e) {
			throw new RuntimeException("初始化beetl配置时发生异常", e);
		}
	}

	private static GroupTemplate me() {
		return me;
	}

	/**
	 * 渲染模板字符串.
	 */
	public static String renderString(String templateString, Map<String, ?> model) {
		return renderString(null, templateString, model);
	}

	/**
	 * 渲染模板字符串.
	 */
	public static String renderString(String templateCacheKey, String templateString, Map<String, ?> model) {
		try {
			StringWriter result = new StringWriter();
			Template template = null;
			if (StringUtils.isBlank(templateCacheKey)) {
				template = me().getStringTemplate(templateString);
			} else {
				template = me().getStringTemplate(templateString, templateCacheKey);
			}
			for (Entry<String, ?> entry : model.entrySet()) {
				template.set(entry.getKey(), entry.getValue());
			}
			template.getText(result);
			return result.toString();
		} catch (Exception e) {
			throw new RuntimeException(String.format("渲染模板时发生异常，模板信息: \r\n %s \r\n,数据信息: %s \r\n", templateString,
					model), e);
		}
	}

	/**
	 * 渲染模板字符串.
	 */
	public static String renderTemplate(String templatePath, Map<String, ?> model) {
		try {
			StringWriter result = new StringWriter();
			Template template = me().getFileTemplate(templatePath);
			for (Entry<String, ?> entry : model.entrySet()) {
				template.set(entry.getKey(), entry.getValue());
			}
			template.getText(result);
			return result.toString();
		} catch (Exception e) {
			throw new RuntimeException(String.format("渲染模板时发生异常，模板文件: %s \r\n,数据信息: %s \r\n", templatePath, model), e);
		}
	}
}
